﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using MAF.Common;
using My.GenCode.Entities;
using My.GenCode.Interface;

namespace My.GenCode.Templates
{
    public class GenDbScript : CodeTemplate
    {
        /// <summary>
        /// 代表某内容块的标签
        /// </summary>
        const string LOOP_TABLE = "Loop:Table";
        const string LOOP_FIELD = "Loop:Field";

        /// <summary>
        /// 定位标签代表的内容块的正则表达式
        /// </summary>
        const string REG_LOGIC = @"(?is)<(Tag>)(.*?)</\1";

        #region 覆盖父类的方法

        public GenDbScript(string tpl, IList<EntityInfo> infos, string desc) : base(tpl, infos, desc) { }

        protected override string ProcTemplate()
        {
            Template tplLogic = new Template(_tpl, REG_LOGIC);
            Template tplTable;
            Template tplField;

            string tableStr = tplLogic.Find(LOOP_TABLE).Groups[2].Value;
            string fieldStr = tplLogic.Find(LOOP_FIELD).Groups[2].Value;

            IList<NameValueCollection> mapField;

            StringBuilder sb = new StringBuilder();
            foreach (EntityInfo info in _infos)
            {
                tplTable = new Template(tableStr, REG_LOGIC);
                tplField = new Template(fieldStr);

                mapField = MAF.Common.ObjectConverter.ToNameValueCollectionList<PropertyInfo>(info.Properties,"<Key>","");
                tplField.Replace(mapField,"\r\n    ,");

                tplTable.Replace(LOOP_FIELD, "     "+tplField.Result);

                tplTable.Type = Template.Types.Normal;
                tplTable.Replace("<TableName>",_nh.EntitiesName);
                sb.Append(tplTable.Result);
            }

            tplLogic.Replace( LOOP_TABLE, sb.ToString() );
            tplLogic.Type = Template.Types.Normal;
            tplLogic.Replace("<FileName>", _nh.DbScriptFileName);
            return tplLogic.Result;
        }

        protected override string OutputFilename()
        {
            return @"DbScript\" + _nh.DbScriptFileName;
        }

        #endregion
    }
}